﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using CRM.Admin.Contracts.Contract.Customer;
using CRM.Admin.Contracts.Contract.Sys;
using CRM.Admin.Contracts.Dto.Customer;
using CRM.Admin.Contracts.Dto.Sys;
using CRM.Admin.Contracts.Model.Customer;
using CRM.Admin.Contracts.Model.Sys;
using CRM.Admin.Services.Service.Customer;
using KingsSharp.Common;
using KingsSharp.Common.Extensions;
using KingsSharp.Common.Filter;
using KingsSharp.Core.Data.Entity;
using KingsSharp.Core.Data.Extensions;
using KingsSharp.Web.Helper;
using KingsSharp.Web.UI;
using CRM.Admin.Contracts.Dto.SalesIinformation;
using Maticsoft.DBUtility;
using System.Data;
using Oracle.DataAccess.Client;

namespace CRM.Admin.Areas.Customer.Controllers
{
    public class CustomerInfoController : Controller
    {
        public const string CUSTOMER_FILEPATH = "BaseCustomerfiles//";
        /// <summary>
        /// Orcale链接字符串
        /// </summary>
        public const string Constring = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.128.250.64) (PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=hl)));Persist Security Info=True;User Id=KSFX; Password=KSFX1";

        public class DicCatalogType
        {
            /// <summary>
            /// 顾客行业
            /// </summary>
            public const string KHHY = "KHHY";

            /// <summary>
            /// 顾客类别
            /// </summary>
            public const string KHLB = "KHLB";

            /// <summary>
            /// 顾客信用评价
            /// </summary>
            public const string KHXYPJ = "KHXYPJ";

            /// <summary>
            /// 钢材品种
            /// </summary>
            public const string GCPZ = "GCPZ";
        }
        public IDictionaryService DictionaryService { get; set; }

        public ICustomerService CustomerService { get; set; }

        public ILinkManService LinkManService { get; set; }

        public ICustomerNatureService CustomerNatureService { get; set; }

        public ITechnologyService TechnologyService { get; set; }
        /// <summary>
        /// 用户业务契约
        /// </summary>
        public IUserInfoService UserInfoService { get; set; }
        /// <summary>
        /// 品种需求
        /// </summary>
        public IVarietyYearService VarietyYearService { get; set; }
        /// <summary>
        /// 顾客协议
        /// </summary>

        public ICustomerAgreementService CustomerAgreementService { get; set; }

        /// <summary>
        /// 是否具备某个页面的权限
        /// </summary>
        /// <param name="actionName">页面名称</param>
        /// <param name="controllerName">控制器名称</param>
        /// <param name="operaName">操作名称</param>
        /// <returns></returns>
        public bool Graent(string actionName, string controllerName, string operaName)
        {
            return UserInfoService.GetUserForPageGarent(actionName, controllerName, operaName, AppVariable.UserData.UserId);
        }
        #region 视图功能
        /// <summary>
        /// 顾客列表
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult CustomerInfoIndex()
        {
            var KHLBdtos = DictionaryService.ItemDictionary.
                 Where(a => a.Parent.Code == DicCatalogType.KHLB).ToList().MapToList<Dictionary, DictionaryDto>();
            var KHHYdtos = DictionaryService.ItemDictionary.
                 Where(a => a.Parent.Code == DicCatalogType.KHHY).ToList().MapToList<Dictionary, DictionaryDto>();
            ViewData[DicCatalogType.KHLB] = KHLBdtos;
            ViewData[DicCatalogType.KHHY] = KHHYdtos;
            ViewBag.creategarent = Graent("CustomerInfoIndex", "CustomerInfo", "insert");
            ViewBag.updategarent = Graent("CustomerInfoIndex", "CustomerInfo", "update");
            ViewBag.deletegarent = Graent("CustomerInfoIndex", "CustomerInfo", "delete");
            ViewBag.detailgarent = Graent("CustomerInfoIndex", "CustomerInfo", "detail");
            return View();
        }
        /// <summary>
        /// 首页显示数据
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var KHLBdtos = DictionaryService.ItemDictionary.
                  Where(a => a.Parent.Code == DicCatalogType.KHLB).ToList().MapToList<Dictionary, DictionaryDto>();
            var KHHYdtos = DictionaryService.ItemDictionary.
                 Where(a => a.Parent.Code == DicCatalogType.KHHY).ToList().MapToList<Dictionary, DictionaryDto>();
            ViewData[DicCatalogType.KHLB] = KHLBdtos;
            ViewData[DicCatalogType.KHHY] = KHHYdtos;
            return View();
        }
        /// <summary>
        /// 新增顾客
        /// </summary>
        /// <returns></returns>
        public ActionResult CustomerInfoAdd()
        {
            var KHHYdtos = DictionaryService.ItemDictionary.
                 Where(a => a.Parent.Code == DicCatalogType.KHHY).ToList().MapToList<Dictionary, DictionaryDto>();
            var KHLBdtos = DictionaryService.ItemDictionary.
                Where(a => a.Parent.Code == DicCatalogType.KHLB).ToList().MapToList<Dictionary, DictionaryDto>();
            var KHXYPJdtos = DictionaryService.ItemDictionary.
              Where(a => a.Parent.Code == DicCatalogType.KHXYPJ).ToList().MapToList<Dictionary, DictionaryDto>();
            ViewData[DicCatalogType.KHHY] = KHHYdtos;
            ViewData[DicCatalogType.KHLB] = KHLBdtos;
            ViewData[DicCatalogType.KHXYPJ] = KHXYPJdtos;
            return View();
        }

        public ActionResult CustomerInfoEdit(Guid CustomerId)
        {
            var KHHYdtos = DictionaryService.ItemDictionary.
              Where(a => a.Parent.Code == DicCatalogType.KHHY).ToList().MapToList<Dictionary, DictionaryDto>();
            var KHLBdtos = DictionaryService.ItemDictionary.
                Where(a => a.Parent.Code == DicCatalogType.KHLB).ToList().MapToList<Dictionary, DictionaryDto>();
            var KHXYPJdtos = DictionaryService.ItemDictionary.
              Where(a => a.Parent.Code == DicCatalogType.KHXYPJ).ToList().MapToList<Dictionary, DictionaryDto>();
            ViewData[DicCatalogType.KHHY] = KHHYdtos;
            ViewData[DicCatalogType.KHLB] = KHLBdtos;
            ViewData[DicCatalogType.KHXYPJ] = KHXYPJdtos;
            var query = CustomerService.Customers.FirstOrDefault(s => s.Id == CustomerId);
            return View(query);
        }
        /// <summary>
        /// 顾客详情
        /// </summary>
        /// <param name="CustomerId"></param>
        /// <returns></returns>
        public ActionResult CustomerInfoDetail(Guid CustomerId)
        {
            CustomerDetailDto customerDetail = new CustomerDetailDto();

            var customer = CustomerService.Customers.FirstOrDefault(a => a.Id == CustomerId);

            var customerDto = customer.MapTo<CustomerDto>();
            customerDto.AddressDescription = customer.CustomerAddress == null ? "" : customer.CustomerAddress.Description;

            var linkMan = LinkManService.LinkMans.Where(a => a.IsDeleted == false).OrderByDescending(a => a.CreatedTime)
                            .FirstOrDefault(a => a.CustomerId == CustomerId);

            var variety = VarietyYearService.VarietyYears.Where(a => a.IsDeleted == false).OrderByDescending(a => a.ParticularYear)
                            .FirstOrDefault(a => a.CustomerId == CustomerId);
            customerDto.SaleSysCode = string.IsNullOrEmpty(customerDto.SaleSysCode) ? "0" : customerDto.SaleSysCode;
            customerDetail.Customer = customerDto;
            customerDetail.LinkMan = linkMan == null ? new LinkManDto() : linkMan.MapTo<LinkManDto>();

            customerDetail.Variety = variety == null ? new VarietyYearDto() : variety.MapTo<VarietyYearDto>();
            ViewBag.prod = GetProd();
            ViewBag.sala = GetSala();
            ViewBag.mode = GetModeName();
            return View(customerDetail);
        }
        /// <summary>
        /// 品种需求
        /// </summary>
        /// <returns></returns>
        public ActionResult GetVarietyYear(int Year, Guid CustomerId)
        {

            var varietyList = VarietyYearService.VarietyYears.Where(a => a.CustomerId == CustomerId).Where(a => a.IsDeleted == false);
            if (Year != 0)
            {

                varietyList = varietyList.Where(a => a.ParticularYear == Year);
            }
            var data = varietyList.OrderByDescending(a => a.ParticularYear).ToList().MapToList<VarietyYear, VarietyYearDto>();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 合同兑换率分析
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOrder(string timeType, string beginTime, string endTime, string prodName, string salaName, string salaNum)
        {
            try
            {
                string where = " where FIN_USER_NUM='" + salaNum + "'";
                if (!string.IsNullOrEmpty(prodName))
                {
                    where += " and PROD_NAME='" + prodName + "'";
                }
                if (!string.IsNullOrEmpty(salaName))
                {
                    where += " and SALE_PROD_NAME='" + salaName + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("资源期") && !string.IsNullOrEmpty(beginTime))
                {
                    where += " and RESO_PERIOD>='" + beginTime + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("资源期") && !string.IsNullOrEmpty(endTime))
                {
                    where += " and RESO_PERIOD<='" + endTime + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("交货期") && !string.IsNullOrEmpty(beginTime))
                {
                    where += " and DELIVERY_DATE_CHR>='" + beginTime + "01" + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("交货期") && !string.IsNullOrEmpty(endTime))
                {
                    where += " and DELIVERY_DATE_CHR<='" + endTime + "31" + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("下发时间") && !string.IsNullOrEmpty(beginTime))
                {
                    where += " and LAUNCH_TIME>='" + beginTime + "01" + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("下发时间") && !string.IsNullOrEmpty(endTime))
                {
                    where += " and LAUNCH_TIME<='" + beginTime + "31" + "'";
                }
                string sql = @"select SALE_PROD_NAME,SUM(ORDER_WT)ORDER_WT,SUM(ORDER_AMT)ORDER_AMT,SUM(FH_WT)FH_WT,SUM(SETTLE_WT)SETTLE_WT,SUM(SETTLE_AMT)SETTLE_AMT from T_ORDER_INFO 
                            " + where + " group by SALE_PROD_NAME";
                OracleDataReader reader = OracleHelper.ExecuteReader(Constring, CommandType.Text, sql);
                List<OrderDto> orderlist = new List<OrderDto>();
                while (reader.Read())
                {
                    OrderDto order = new OrderDto();
                    order.SalesVariety = reader["SALE_PROD_NAME"].ToString();
                    order.OrderQuantity = Convert.ToDecimal(reader["ORDER_WT"]);
                    order.OrderPrivceCount = Math.Round(Convert.ToDecimal(reader["ORDER_AMT"]), 2);
                    order.OrderPrice = order.OrderPrivceCount != 0 && order.OrderQuantity != 0 ? Math.Round(order.OrderPrivceCount / order.OrderQuantity, 2) : 0;
                    order.DeliveryVolume = Convert.ToDecimal(reader["FH_WT"]);
                    order.SettlementAmount = Convert.ToDecimal(reader["SETTLE_WT"]);
                    order.SettlementPrivceCount = Math.Round(Convert.ToDecimal(reader["SETTLE_AMT"]), 2);
                    order.SettlementPrivce = order.SettlementPrivceCount != 0 && order.SettlementAmount != 0 ? Math.Round(order.SettlementPrivceCount / order.SettlementAmount, 2) : 0;
                    orderlist.Add(order);
                }
                return Json(orderlist, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {

                return Json(null, JsonRequestBehavior.AllowGet);
            }

        }
        /// <summary>
        /// 顾客订单分析
        /// </summary>
        /// <param name="timeType"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="prodName"></param>
        /// <param name="salaName"></param>
        /// <param name="salaNum"></param>
        /// <returns></returns>
        public ActionResult GetCustomerOrder(string timeType, string beginTime, string endTime, string prodName, string salaName, string salaNum, string modeName)
        {
            try
            {
                string where = " where FIN_USER_NUM='" + salaNum + "'";
                if (!string.IsNullOrEmpty(prodName))
                {
                    where += " and PROD_NAME='" + prodName + "'";
                }
                if (!string.IsNullOrEmpty(salaName))
                {
                    where += " and SALE_PROD_NAME='" + salaName + "'";
                }
                if (!string.IsNullOrEmpty(modeName))
                {
                    where += " and SETTLE_MODE_NAME='" + modeName + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("资源期") && !string.IsNullOrEmpty(beginTime))
                {
                    where += " and RESO_PERIOD>='" + beginTime + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("资源期") && !string.IsNullOrEmpty(endTime))
                {
                    where += " and RESO_PERIOD<='" + endTime + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("交货期") && !string.IsNullOrEmpty(beginTime))
                {
                    where += " and DELIVERY_DATE_CHR>='" + beginTime + "01" + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("交货期") && !string.IsNullOrEmpty(endTime))
                {
                    where += " and DELIVERY_DATE_CHR<='" + endTime + "31" + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("下发时间") && !string.IsNullOrEmpty(beginTime))
                {
                    where += " and LAUNCH_TIME>='" + beginTime + "01" + "'";
                }
                if (!string.IsNullOrEmpty(timeType) && timeType.Equals("下发时间") && !string.IsNullOrEmpty(endTime))
                {
                    where += " and LAUNCH_TIME<='" + beginTime + "31" + "'";
                }
                //string sql = @"select SALE_PROD_NAME,SUM(ORDER_WT)ORDER_WT,SUM(ORDER_AMT)ORDER_AMT,SUM(FH_WT)FH_WT,SUM(SETTLE_WT)SETTLE_WT,SUM(SETTLE_AMT)SETTLE_AMT from T_ORDER_INFO 
                //            " + where + " group by SALE_PROD_NAME";
                string sql = @"select a.SALE_PROD_NAME,a.ORDER_WT,a.ORDER_AMT,a.FH_WT,a.SETTLE_WT,a.SETTLE_AMT,
                                (select NVL(SUM(SETTLE_AMT),0) from T_ORDER_INFO where  SALE_PROD_NAME=a.SALE_PROD_NAME and RESO_PERIOD=to_char(add_months(sysdate,-1),'yyyymm'))Prev_Privce,
                                (select NVL(SUM(SETTLE_WT),0) from T_ORDER_INFO where  SALE_PROD_NAME=a.SALE_PROD_NAME and RESO_PERIOD=to_char(add_months(sysdate,-1),'yyyymm'))Prev_Settle_wt,
                                (select NVL(SUM(SETTLE_AMT),0) from T_ORDER_INFO where SALE_PROD_NAME=a.SALE_PROD_NAME and RESO_PERIOD=to_char(add_months(sysdate,-12),'yyyymm'))PrevYear_Privce,
                                (select NVL(SUM(SETTLE_WT),0) from T_ORDER_INFO where SALE_PROD_NAME=a.SALE_PROD_NAME and RESO_PERIOD=to_char(add_months(sysdate,-12),'yyyymm'))PrevYear_Settle_wt from 
                            (select SALE_PROD_NAME,SUM(ORDER_WT)ORDER_WT,SUM(ORDER_AMT)ORDER_AMT,SUM(FH_WT)FH_WT,SUM(SETTLE_WT)SETTLE_WT,SUM(SETTLE_AMT)SETTLE_AMT from T_ORDER_INFO 
                            " + where + " group by SALE_PROD_NAME)a";
                // string sql = "select RESO_PERIOD,ORDER_WT,SALE_PROD_NAME from T_ORDER_INFO where SALE_PROD_NAME='小锌花冲压镀锌' and RESO_PERIOD='201505'";
                OracleDataReader reader = OracleHelper.ExecuteReader(Constring, CommandType.Text, sql);
                List<OrderDto> orderlist = new List<OrderDto>();
                while (reader.Read())
                {
                    OrderDto order = new OrderDto();
                    order.SalesVariety = reader["SALE_PROD_NAME"].ToString();
                    order.OrderQuantity = Convert.ToDecimal(reader["ORDER_WT"]);
                    order.OrderPrivceCount = Math.Round(Convert.ToDecimal(reader["ORDER_AMT"]), 2);
                    order.OrderPrice = order.OrderPrivceCount != 0 && order.OrderQuantity != 0 ? Math.Round(order.OrderPrivceCount / order.OrderQuantity, 2) : 0;
                    order.DeliveryVolume = Convert.ToDecimal(reader["FH_WT"]);
                    order.SettlementAmount = Convert.ToDecimal(reader["SETTLE_WT"]);
                    order.SettlementPrivceCount = Math.Round(Convert.ToDecimal(reader["SETTLE_AMT"]), 2);
                    order.PreviousSettlemenPrivce = Convert.ToDecimal(reader["Prev_Privce"]);
                    order.LastPeriodPrivce = Convert.ToDecimal(reader["PrevYear_Privce"]);
                    order.PreviousAmountCount = Convert.ToDecimal(reader["Prev_Settle_wt"]);
                    order.LastPeriodAmcountCount = Convert.ToDecimal(reader["PrevYear_Settle_wt"]);
                    order.SettlementPrivce = order.SettlementPrivceCount != 0 && order.SettlementAmount != 0 ? Math.Round(order.SettlementPrivceCount / order.SettlementAmount, 2) : 0;
                    orderlist.Add(order);
                }
                return Json(orderlist, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {

                return Json(null, JsonRequestBehavior.AllowGet);
            }

        }
        /// <summary>
        /// 查询所有销售品种名称
        /// </summary>
        /// <returns></returns>
        public List<string> GetSala()
        {
            string sql = "select SALE_PROD_NAME from T_ORDER_INFO group by SALE_PROD_NAME";
            OracleDataReader reader = OracleHelper.ExecuteReader(Constring, CommandType.Text, sql);
            List<string> prodList = new List<string>();
            while (reader.Read())
            {
                prodList.Add(reader["SALE_PROD_NAME"].ToString());
            }
            return prodList;
        }
        /// <summary>
        /// 付款方式
        /// </summary>
        /// <returns></returns>
        public List<string> GetModeName()
        {
            string sql = "select SETTLE_MODE_NAME from T_ORDER_INFO group by SETTLE_MODE_NAME";
            OracleDataReader reader = OracleHelper.ExecuteReader(Constring, CommandType.Text, sql);
            List<string> modeList = new List<string>();
            while (reader.Read())
            {
                modeList.Add(reader["SETTLE_MODE_NAME"].ToString());
            }
            return modeList;
        }
        /// <summary>
        /// 查询所有产品大类
        /// </summary>
        /// <returns></returns>
        public List<string> GetProd()
        {
            string sql = "select PROD_NAME from T_ORDER_INFO group by PROD_NAME";
            OracleDataReader reader = OracleHelper.ExecuteReader(Constring, CommandType.Text, sql);
            List<string> prodList = new List<string>();
            while (reader.Read())
            {
                prodList.Add(reader["PROD_NAME"].ToString());
            }
            return prodList;
        }
        /// <summary>
        /// 顾客订单收发存分析
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOrderTransmitReceive(string prodName, string salaName, string salaNum)
        {
            string where = "where FIN_USER_NUM='" + salaNum + "'";
            if (!string.IsNullOrEmpty(prodName))
            {
                where += " and PROD_NAME='" + prodName + " '";
            }
            if (!string.IsNullOrEmpty(salaName))
            {
                where += " and SALE_PROD_NAME='" + salaName + "'";
            }
            string sql = "select SALE_PROD_NAME,SUM(RK_WT)RK_WT,SUM(CK_WT)CK_WT,SUM(KC_WT)KC_WT from T_STOCK_INFO " + where + " group by  SALE_PROD_NAME";
            OracleDataReader reader = OracleHelper.ExecuteReader(Constring, CommandType.Text, sql);
            List<OrderTransmitReceiveDto> orderTransmList = new List<OrderTransmitReceiveDto>();
            while (reader.Read())
            {
                OrderTransmitReceiveDto ordertran = new OrderTransmitReceiveDto();
                ordertran.SalesVariety = reader["SALE_PROD_NAME"].ToString();
                ordertran.ScheduledReceipt = Convert.ToDecimal(reader["RK_WT"]);
                ordertran.OutgoingQuantity = Convert.ToDecimal(reader["CK_WT"]);
                ordertran.InventoryQuantity = Convert.ToDecimal(reader["KC_WT"]);
                orderTransmList.Add(ordertran);

            }
            return Json(orderTransmList, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 库龄分析
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOldlibrary(string prodName, string salaName, string salaNum)
        {
            string where = " where a.FIN_USER_NUM = '" + salaNum + "'";
            if (!string.IsNullOrEmpty(prodName))
            {
                where += " and a.PROD_NAME='" + prodName + "'";
            }
            if (!string.IsNullOrEmpty(salaName))
            {
                where += " and a.SALE_PROD_NAME='" + salaName + "'";
            }
            string sql = @"SELECT a.SALE_PROD_NAME,
                            SUM(DECODE(a.STOCK_AGE_CODE,'1',a.KC_WT,0)) AS wt30,
                            SUM(DECODE(a.STOCK_AGE_CODE, '2', a.KC_WT, 0)) AS wt30_60,
                            SUM(DECODE(a.STOCK_AGE_CODE, '3', a.KC_WT, 0)) AS wt60_90,
                            SUM(DECODE(a.STOCK_AGE_CODE, '4', a.KC_WT, 0)) AS wt90_180,
                            SUM(DECODE(a.STOCK_AGE_CODE, '5', a.KC_WT, 0)) AS wt180_365,
                            SUM(DECODE(a.STOCK_AGE_CODE, '6', a.KC_WT, 0)) AS wt365 FROM T_STOCK_AGE a
                         " + where + " group by a.SALE_PROD_NAME";
            OracleDataReader reader = OracleHelper.ExecuteReader(Constring, CommandType.Text, sql);
            List<OldLibraryDto> oldlibraryList = new List<OldLibraryDto>();
            while (reader.Read())
            {
                OldLibraryDto oldlivrary = new OldLibraryDto();
                oldlivrary.SaleProdName = reader["SALE_PROD_NAME"].ToString();
                oldlivrary.KcWt30 = Convert.ToDecimal(reader["wt30"]);
                oldlivrary.KcWt31_61 = Convert.ToDecimal(reader["wt30_60"]);
                oldlivrary.KcWt62_92 = Convert.ToDecimal(reader["wt60_90"]);
                oldlivrary.KcWt93_182 = Convert.ToDecimal(reader["wt90_180"]);
                oldlivrary.KcWt183_365 = Convert.ToDecimal(reader["wt180_365"]);
                oldlivrary.KcWt365 = Convert.ToDecimal(reader["wt365"]);
                oldlivrary.kwCount = oldlivrary.KcWt30 + oldlivrary.KcWt31_61 + oldlivrary.KcWt62_92 + oldlivrary.KcWt93_182 + oldlivrary.KcWt183_365 + oldlivrary.KcWt365;
                oldlibraryList.Add(oldlivrary);
            }
            return Json(oldlibraryList, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 顾客协议
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCustomerAgreement(Guid CustomerId, string begintime, string endtime, string prodName)
        {
            try
            {
                var list = CustomerAgreementService.CustomerAgreements.Where(a => a.CustomerId == CustomerId);
                if (!string.IsNullOrEmpty(prodName))
                {
                    list = list.Where(a => a.ProdName.Contains(prodName));
                }
                var agrlist = list.ToList().MapToList<CustomerAgreement, CustomerAgreementDto>();
                return Json(agrlist, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                return Json(null, JsonRequestBehavior.AllowGet);
            }

        }
        /// <summary>
        /// 添加联系人
        /// </summary>
        /// <returns></returns>
        public ActionResult LinkManAdd(Guid CustomerId)
        {
            ViewBag.CustomerId = CustomerId;
            return View();
        }
        /// <summary>
        /// 添加生产工艺
        /// </summary>
        /// <param name="CustomerId"></param>
        /// <returns></returns>
        public ActionResult TechnologyAdd(Guid CustomerId)
        {
            ViewBag.CustomerId = CustomerId;
            return View();
        }
        /// <summary>
        /// 生产工艺编辑
        /// </summary>
        /// <param name="CustomerId"></param>
        /// <returns></returns>
        public ActionResult TechnologyEdit(Guid CustomerId, Guid Id)
        {
            ViewBag.CustomerId = CustomerId;
            var dto = TechnologyService.Technologys.FirstOrDefault(a => a.CustomerId == CustomerId && a.Id == Id).MapTo<TechnologyDto>();
            return View(dto);
        }
        /// <summary>
        /// 顾客选择
        /// </summary>
        /// <param name="Multi">是否允许多选，默认false</param>
        /// <returns></returns>
        public ActionResult CustomerCheck(bool Multi = false)
        {
            ViewBag.Multi = Multi.ToString().ToLower();
            return View();
        }
        #endregion

        #region 数据功能
        /// <summary>
        /// 新增联系人
        /// </summary>
        /// <param name="linkmanDto"></param>
        /// <returns></returns>
        public ActionResult LinkManInsert(LinkManDto linkmanDto)
        {
            linkmanDto.CheckNotNull(nameof(linkmanDto));

            var result = LinkManService.Insert(linkmanDto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "联系人“{0}”添加成功。".FormatWith(linkmanDto.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 删除联系人
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public ActionResult LinkManAddDelete(Guid UserId)
        {
            UserId.CheckNotEmpty("UserId");
            Guid[] id = new Guid[] { UserId };
            var result = LinkManService.Delete(id);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "联系人删除成功。";
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 新增顾客性质
        /// </summary>
        /// <returns></returns>
        public ActionResult CustomerNatureInsert(CustomerNatureDto custnatureDto)
        {
            custnatureDto.CheckNotNull(nameof(custnatureDto));

            var result = CustomerNatureService.Insert(custnatureDto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "顾客性质添加成功。";
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 删除顾客性质
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public ActionResult CustomerNatureDelete(Guid UserId)
        {
            UserId.CheckNotEmpty("UserId");
            Guid[] id = new Guid[] { UserId };
            var result = CustomerNatureService.Delete(id);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "顾客性质删除成功。";
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult TechnologyInsert(TechnologyDto technologyDto)
        {
            technologyDto.CheckNotNull("technologyDto");

            var result = TechnologyService.Insert(technologyDto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "生产工艺添加成功。";
            }
            return Json(new AjaxResult(msg, msgType));
        }

        public ActionResult TechnologyUpdate(TechnologyDto technologyDto)
        {
            technologyDto.CheckNotNull("technologyDto");

            var result = TechnologyService.Update(technologyDto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "生产工艺更新成功。";
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult TechnologyDelete(Guid UserId)
        {
            UserId.CheckNotEmpty("UserId");
            Guid[] id = new Guid[] { UserId };
            var result = TechnologyService.Delete(id);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "生产工艺删除成功。";
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult CustomerInsert(CustomerDto customerDto)
        {
            customerDto.CheckNotNull(nameof(customerDto));
            Guid? code = customerDto.CustomerAddressId;

            customerDto.CreateId = AppVariable.UserData.UserId;
            customerDto.CreateLogCode = AppVariable.UserData.LoginCode;
            customerDto.CreateName = AppVariable.UserData.UserName;
            var result = CustomerService.Insert(customerDto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "顾客“{0}”添加成功。".FormatWith(customerDto.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }

        public ActionResult CustomerUpdate(CustomerDto customerDto)
        {
            customerDto.CheckNotNull(nameof(customerDto));
            customerDto.LastEditId = AppVariable.UserData.UserId;
            customerDto.LastEditLogCode = AppVariable.UserData.LoginCode;
            customerDto.LastEditName = AppVariable.UserData.UserName;
            customerDto.LastEditTime = DateTime.Now;
            var result = CustomerService.Update(customerDto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "顾客“{0}”更新成功。".FormatWith(customerDto.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult CustomerInfoDelete(Guid UserId, string UserName)
        {
            Guid[] id = new Guid[] { UserId };
            var result = CustomerService.Delete(id);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "顾客“{0}”删除成功。".FormatWith(UserName);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult GetCustmerInfoGridData()
        {
            GridRequest request = new GridRequest(Request);
            Expression<Func<Contracts.Model.Customer.Customer, bool>> predicate = FilterHelper.GetExpression<Contracts.Model.Customer.Customer>(request.FilterGroup);
            int total;
            var data = CustomerService.Customers.
                Where(a => a.IsDeleted == false).
                Where<Contracts.Model.Customer.Customer, Guid>(predicate, request.PageCondition, out total).
                Select(dto => new
                {
                    dto.Id,
                    dto.Name,
                    dto.ShortName,
                    dto.Code,
                    dto.SaleSysCode,
                    dto.CustomerAddress.Province,
                    dto.CustomerAddress.ProvinceCode,
                    dto.CustomerAddress.City,
                    dto.CustomerAddress.Borough,
                    dto.CustomerAddress.Description,
                    dto.Scale,
                    dto.Business,
                    dto.Industry,
                    dto.CreditInfo,
                    dto.TicketBank,
                    dto.TicketBankAccount,
                    dto.Profiles,
                    dto.CreditRatings,
                    dto.AgreementFilishProfiles,
                    ParentName = dto.ParentCustomer.Name,
                    dto.CooperationState
                }).ToList();

            return Json(new GridData<object>(data, total), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 顾客图片、附件上传
        /// </summary>
        /// <returns></returns>
        public ActionResult UploaderProcess()
        {
            UploaderResult result = null;
            try
            {
                string path = CUSTOMER_FILEPATH;
                result = new WebUploader().Process(Request, path, file => Guid.NewGuid().ToString() + "_" + file.FileName);
            }
            catch (Exception ex)
            {
                result = new UploaderResult { Message = ex.Message };
                throw new Exception(ex.Message);
            }
            return Json(result);
        }
        #endregion
    }
}